package com.niubility.shiro.realms;

import com.niubility.entity.Department;
import com.niubility.server.IDepartmentService;
import com.niubility.server.IPwdService;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;


@Controller
public class jdbcRealm extends AuthenticatingRealm{
        @Resource
        private IDepartmentService departmentService;
        @Resource
        private IPwdService pwdService ;
        @Override
        public String getName() {
            return "FirstRealm";

        }

        @Override
        public void setName(String name) {
            super.setName("FirstRealm");
        }

    @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            //1.把AuthenticationToken转化成UsernamePasswordToken
            UsernamePasswordToken uptoken = (UsernamePasswordToken)token;
            //2.从UsernamePasswordToken 中获取userName,userPhone
            String depAcount=uptoken.getUsername();
            String userPwd=uptoken.getPassword().toString();
            Department department =this.departmentService.loadDepByAcount(depAcount);
            int depId=department.getDepId();
            //通过userid找密码
            ////System.out.println(this.pwdService.LoadById(depId));

            //获取到的是加盐之后的值
            String userPassword=this.pwdService.CipherEncryptionBySHA1(userPwd,depAcount);
            //3.调用数据库的方法，从数据库中 查询userName 对应的用户记录
            ////System.out.println("从数据库中获取"+depAcount+"所对应 的用户信息。");
            if(department==null){
                throw new UnknownAccountException("社团不存在不存在!");
            }

            //以下信息是从数据库中获取的
            //principal ：认证的实体信息	  可以是userName也可以是数据表对应的用户的实体类对象
            Object principal = department;
            Object credentials = pwdService.LoadById(depId).getUserPwd();
            String realmName = getName();
            //realmName:当前对象的name调用父类的getName方法
            //盐值：
            ByteSource credentialsSalt=ByteSource.Util.bytes(depAcount);
            SimpleAuthenticationInfo info=null;
            info=new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName );
            return info;
        }
    public static void main(String[] args) {
        String algorithmName="SHA1";
        Object source="12345";
        Object salt=ByteSource.Util.bytes("13109512895");
        int hashIterations=1024;
        Object result=new SimpleHash(algorithmName, source, salt, hashIterations);
        ////System.out.println(result);
    }

    }
